package com.meeting.y.util;

import java.util.*;

public class GeoHash {
    public static final double MINLAT = -90;
    public static final double MAXLAT = 90;
    public static final double MINLNG = -180;
    public static final double MAXLNG = 180;

    private static int numbits = 3 * 5; //经纬度单独编码长度

    private static double minLat;
    private static double minLng;

    private final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p',
            'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

    //定义编码映射关系
    final static HashMap<Character, Integer> lookup = new HashMap<Character, Integer>();
    //初始化编码映射内容
    static {
        int i = 0;
        for (char c : digits)
            lookup.put(c, i++);
    }

    public GeoHash(){
        setMinLatLng();
    }

    public String encode(double lon, double lat) {
        BitSet latbits = getBits(lat, -90, 90);
        BitSet lonbits = getBits(lon, -180, 180);
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < numbits; i++) {
            buffer.append( (lonbits.get(i))?'1':'0');
            buffer.append( (latbits.get(i))?'1':'0');
        }
        String code = base32(Long.parseLong(buffer.toString(), 2));
        //Log.i("okunu", "encode  lat = " + lat + "  lng = " + lon + "  code = " + code);
        return code;
    }

    public String encodeSide(double lon, double lat) {
        BitSet latbits = getSideBits(lat, -90, 90,minLat/2);
        BitSet lonbits = getSideBits(lon, -180, 180,minLng/2);
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < numbits; i++) {
            buffer.append( (lonbits.get(i))?'1':'0');
            buffer.append( (latbits.get(i))?'1':'0');
        }
        String code = base32(Long.parseLong(buffer.toString(), 2));
        //Log.i("okunu", "encode  lat = " + lat + "  lng = " + lon + "  code = " + code);
        return code;
    }

    public ArrayList<String> getArroundGeoHash(double lon, double lat){
        //Log.i("okunu", "getArroundGeoHash  lat = " + lat + "  lng = " + lon);
        ArrayList<String> list = new ArrayList<>();
        double uplat = lat + minLat;
        double downLat = lat - minLat;

        double leftlng = lon - minLng;
        double rightLng = lon + minLng;

        String leftUp = encode(leftlng, uplat);
        list.add(leftUp);

        String leftMid = encode(leftlng, lat);
        list.add(leftMid);

        String leftDown = encode(leftlng, downLat);
        list.add(leftDown);

        String midUp = encode(lon, uplat);
        list.add(midUp);

        String midMid = encode(lon, lat);
        list.add(midMid);

        String midDown = encode(lon, downLat);
        list.add(midDown);

        String rightUp = encode(rightLng, uplat);
        list.add(rightUp);

        String rightMid = encode(rightLng, lat);
        list.add(rightMid);

        String rightDown = encode(rightLng, downLat);
        list.add(rightDown);

        //Log.i("okunu", "getArroundGeoHash list = " + list.toString());
        return list;
    }

    //根据经纬度和范围，获取对应的二进制
    private BitSet getBits(double lat, double floor, double ceiling) {
        BitSet buffer = new BitSet(numbits);
        for (int i = 0; i < numbits; i++) {
            double mid = (floor + ceiling) / 2;
            if (lat >= mid) {
                buffer.set(i);
                floor = mid;
            } else {
                ceiling = mid;
            }
        }
        return buffer;
    }

    //偏心算法，获取二进制。将0.75 算0,0.25算1
    /**
     * 考虑了3个方案
     * 1.处理拆分 为偏分 计算中标线*1.5            double mid = (floor + ceiling) / 2 * 1.5; //会有不均分问题
     * 2.中线偏移，            double mid = (floor + ceiling) / 2 + side; //也可以，会有左上 顶 部，是最后一步处理，还是每次处理问题
     * 3.坐标偏移，将坐标 向左下 增加side，如果计算坐标超过 最大值，减去最大值
     * @param lat
     * @param floor
     * @param ceiling
     * @param side
     * @return
     */
    private BitSet getSideBits(double lat, double floor, double ceiling,double side) {
        System.out.println(lat+"/"+floor+"/"+ceiling+"/"+side);
        lat = getSideLat(lat,floor,ceiling,side);//进行坐标偏移
        System.out.println(lat);
        BitSet buffer = new BitSet(numbits);
        for (int i = 0; i < numbits; i++) {
            //还没有验证，好像会导致 部分区域比较大
            double mid = (floor + ceiling) / 2 ;
            if (lat >= mid) {
                buffer.set(i);
                floor = mid;
            } else {
                ceiling = mid;
            }
        }
        return buffer;
    }

    private double getSideLat(double lat, double floor, double ceiling,double side){
        double return_lat = lat + side;
        if(return_lat > ceiling){//偏移后，超过最大值，移到左上
            return_lat = return_lat - (ceiling - floor);
        }
        return return_lat;
    }

    //将经纬度合并后的二进制进行指定的32位编码
    private String base32(long i) {
        char[] buf = new char[65];
        int charPos = 64;
        boolean negative = (i < 0);
        if (!negative){
            i = -i;
        }
        while (i <= -32) {
            buf[charPos--] = digits[(int) (-(i % 32))];
            i /= 32;
        }
        buf[charPos] = digits[(int) (-i)];
        if (negative){
            buf[--charPos] = '-';
        }
        return new String(buf, charPos, (65 - charPos));
    }

    private void setMinLatLng() {
        minLat = MAXLAT - MINLAT;
        for (int i = 0; i < numbits; i++) {
            minLat /= 2.0;
        }
        minLng = MAXLNG - MINLNG;
        for (int i = 0; i < numbits; i++) {
            minLng /= 2.0;
        }
    }

    //根据二进制和范围解码
    private double decode(BitSet bs, double floor, double ceiling) {
        double mid = 0;
        for (int i=0; i<bs.length(); i++) {
            mid = (floor + ceiling) / 2;
            if (bs.get(i))
                floor = mid;
            else
                ceiling = mid;
        }
        return mid;
    }

    //对编码后的字符串解码
    public double[] decode(String geohash) {
        StringBuilder buffer = new StringBuilder();
        for (char c : geohash.toCharArray()) {
            int i = lookup.get(c) + 32;
            buffer.append( Integer.toString(i, 2).substring(1) );
        }

        BitSet lonset = new BitSet();
        BitSet latset = new BitSet();

        //偶数位，经度
        int j =0;
        for (int i=0; i< numbits*2;i+=2) {
            boolean isSet = false;
            if ( i < buffer.length() )
                isSet = buffer.charAt(i) == '1';
            lonset.set(j++, isSet);
        }

        //奇数位，纬度
        j=0;
        for (int i=1; i< numbits*2;i+=2) {
            boolean isSet = false;
            if ( i < buffer.length() )
                isSet = buffer.charAt(i) == '1';
            latset.set(j++, isSet);
        }

        double lon = decode(lonset, -180, 180);//经
        double lat = decode(latset, -90, 90);//维

        return new double[] { lon,lat};
    }

    public static void main(String[] args)  throws Exception{
        System.out.println(TimeUtil.getUnionkeyDateTime());
//[116.3967,44.9999]和[116.3967,45.0009]
        GeoHash geohash = new GeoHash();
        String s = geohash.encode(116.3967, 45.9999);
        String s1 = geohash.encodeSide(116.3967, 45.9999);

        String s0 = geohash.encode(116.3967, 45.0009);
        String s01 = geohash.encodeSide(116.3967, 45.0009);

        String s_1 = geohash.encode(116.248283, 40.222012);
        String s_11 = geohash.encodeSide(116.248283, 40.222012);
        String s_2 = geohash.encode(121.48789949, 31.24916171);
        String s_21 = geohash.encodeSide(121.48789949, 31.24916171);

        System.out.println(s+"-"+s1);
        System.out.println(s0+"-"+s01);
        System.out.println(s_1+"-"+s_11);
        System.out.println(s_2+"-"+s_21);

        List<String> list = geohash.getArroundGeoHash(116.3967, 45.9999);
        System.out.println(Arrays.toString(list.toArray()));
        List<String> list1 = geohash.getArroundGeoHash(116.3967, 45.0009);
        System.out.println(Arrays.toString(list1.toArray()));
        List<String> list2 = geohash.getArroundGeoHash(116.248283, 40.222012);
        System.out.println(Arrays.toString(list2.toArray()));
        List<String> list3 = geohash.getArroundGeoHash(121.48789949, 31.24916171);
        System.out.println(Arrays.toString(list3.toArray()));

        System.out.println(TimeUtil.getUnionkeyDateTime());
//        double[] geo = geohash.decode(s);
//        System.out.println(geo[0]+" "+geo[1]);
    }
}